package com.bankcard.util;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

public class I18nManager {
    private static final I18nManager INSTANCE = new I18nManager();
    private static final String BUNDLE_NAME = "com.bankcard.i18n.messages";
    private final ConcurrentHashMap<Locale, ResourceBundle> bundleCache = new ConcurrentHashMap<>();
    private final ThreadLocal<Locale> currentLocale = ThreadLocal.withInitial(Locale::getDefault);

    private I18nManager() {
        // Private constructor to prevent instantiation
    }

    public static I18nManager getInstance() {
        return INSTANCE;
    }

    public void setLocale(Locale locale) {
        currentLocale.set(locale);
    }

    public Locale getCurrentLocale() {
        return currentLocale.get();
    }

    private ResourceBundle getBundle(Locale locale) {
        return bundleCache.computeIfAbsent(locale, l -> {
            try {
                return ResourceBundle.getBundle(BUNDLE_NAME, l);
            } catch (MissingResourceException e) {
                System.err.println("Resource bundle not found for locale: " + l + ". Falling back to default locale.");
                return ResourceBundle.getBundle(BUNDLE_NAME, Locale.getDefault());
            }
        });
    }

    public String getString(String key) {
        try {
            return getBundle(currentLocale.get()).getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

    public String getString(String key, Object... args) {
        try {
            return String.format(getBundle(currentLocale.get()).getString(key), args);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

    public static String getString(String key, Locale locale) {
        try {
            return getInstance().getBundle(locale).getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }
}